package cn.lotusnut.dynamicscheduled.util;

import cn.lotusnut.dynamicscheduled.entity.task.TaskEntity;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;

/**
 * @Author JiangMing Zhou
 * @Date 2023/4/23 10:24
 * @Version 1.8
 */
public class TaskUtil {

    public static Runnable getRunnable(TaskEntity taskEntity) {
        return () -> {
            Class<?> clazz;
            try {
                clazz = Class.forName(taskEntity.getClassName());
                Object bean = BeanUtil.getBean(clazz);
                Method method = ReflectionUtils.findMethod(clazz, taskEntity.getMethodName());
                ReflectionUtils.invokeMethod(method, bean);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        };
    }

    public static Trigger getTrigger(TaskEntity taskEntity) {
        return triggerContext -> {
            CronTrigger trigger = new CronTrigger(taskEntity.getCron());
            return trigger.nextExecutionTime(triggerContext);
        };
    }
}
